import React, {useRef, useState} from "react";
import {Button, Paper, Popper, TextField} from "@material-ui/core";
import {Autocomplete} from "@material-ui/lab";
import Grid from "@material-ui/core/Grid";


export default function MenuMultiSelect({name, dataSource, itemName, handleChange, selectAll}) {
  const [open, setOpen] = useState(false);
  const timer = useRef(-1);

  const setOpenByTimer = (isOpen) => {
    clearTimeout(timer.current);
    timer.current = window.setTimeout(() => {
      setOpen(isOpen);
    }, 200);
  };

  const handlePopperActions = (props) => {

    const addAllClick = () => {
      clearTimeout(timer.current);
      selectAll();
      setOpenByTimer(!open);
    };

    return (
      <Popper {...props}>
        {props.children}
        <Grid container justify="flex-end">
          <Grid item component={Paper}>
            <Button variant="outlined" onClick={addAllClick}>
              Select All
            </Button>
          </Grid>
        </Grid>
      </Popper>
    )
  }

  return (
    <Autocomplete
      PopperComponent={handlePopperActions}
      multiple
      options={dataSource}
      onChange={handleChange}
      defaultValue={itemName}
      value={itemName}
      getOptionLabel={(option) => option.name}
      filterSelectedOptions={true}
      onOpen={() => setOpenByTimer(!open)}
      onClose={() => setOpenByTimer(!open)}
      open={open}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="outlined"
          label={name}
          placeholder={`Search for ${name}...`}
        />
      )}
    />
  );
}
